<?php
/**
 * Create By: PhpStorm
 * User: yihua
 * File: UserCoupon.php
 * Date: 2017/1/6
 * Time: 2:21
 */

namespace app\api\model\dao;

use think\Db;
use think\Model;
use app\library\Flag;

class UserCoupon extends model
{
    protected $table = 'user_coupon';

    /**
     * @param $user_id
     * @param $coupon_id
     * @param $coupon_info
     * @return false|int
     */
    public function addCoupon($user_id, $coupon_id, $coupon_info)
    {
        $param['user_id'] = $user_id;
        $param['coupon_id'] = $coupon_id;
        $param['coupon_info'] = json_encode($coupon_info);
        $param['create_time'] = time();
        $param['update_time'] = time();
        $this->data($param);
        return $this->save();
    }

    /**
     * @param $user_id
     * @return false|\PDOStatement|string|\think\Collection
     */
    public function getCouponByUserid($user_id)
    {
        $conds = array(
            'user_id' => $user_id,
            'status' => Flag::USER_COUPON_STATUS_NOT_USED,
        );
        $field = array(
            'id',
            'status',
            'create_time',
            'update_time',
        );

        return $this->where($conds)->field($field, true)->select();
    }

    public function getHistoryCouponByUserid($user_id)
    {
        $in = sprintf("%s,%s", Flag::USER_COUPON_STATUS_USED, Flag::USER_COUPON_STATUS_EXPIRED);
        $conds = array(
            'user_id' => $user_id,
            'status' => ["in", $in],
        );
        $field = array(
            'create_time',
            'update_time',
        );
        $ret = Db::table($this->table)->where($conds)->field($field, true)->select();
        //return $ret;
        $data = [];
        if (empty($ret)) {
            return $ret;
        } else {

            foreach ($ret as $key => $value) {
                $temp = json_decode($value['coupon_info'], true);
                $temp['start_time'] = date('Y-m-d', $temp['start_time']);
                $temp['end_time'] = date('Y-m-d', $temp['end_time']);
                $temp['type'] = Flag::$coupon_type[$temp['type']];
                $data[] = array_merge($value, $temp);
                unset($data[$key]['coupon_info']);
            }
            return $data;
        }
    }

    /**
     * @param $param
     * @return false|int
     */
    public function updateCoupon($conds, $param)
    {
        return $this->isUpdate(true)->where($conds)->allowField(true)->save($param);
    }

    public function expireCoupon($user_id, $coupon_id)
    {
        $conds = [
            'user_id' => $user_id,
            'coupon_id' => $coupon_id,
        ];
        $data = array(
            'status' => Flag::USER_COUPON_STATUS_EXPIRED,
        );
        return $this->isUpdate(true)->save($data, $conds);
    }

    public function getStartTimeAttr($value)
    {
        return date('Y-m-d H:i:s', $value);

    }
}